package me.zhengjie.ffmpeg;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FFmpegUtils {

    /**
     * 转码视频为m3u8
     * @param videoSourceFilePath				源视频
     * @param audioTargetFilePath			目标文件夹
     * @throws IOException
     * @throws InterruptedException
     */
    public static Boolean audioByVideo(String videoSourceFilePath, String audioTargetFilePath) {
        try {
            log.info("Get Audio By Video Start, Source={}", videoSourceFilePath);
            long beginTime = System.currentTimeMillis();
            File outputFile = new File(audioTargetFilePath);
            if(outputFile.exists()){
                outputFile.delete();
            }
            File outputDir = outputFile.getParentFile();
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            // 执行的命令
            ArrayList<String> command = new ArrayList<>();
            command.add("ffmpeg");
            command.add("-i");
            command.add(videoSourceFilePath);
            command.add("-vcodec");
            command.add("h264");
            command.add(audioTargetFilePath);
            log.info("Audio By Video Command = {}", StringUtils.join(command," "));
            RuntimeUtils.run(command);
            long timeConsuming = System.currentTimeMillis() - beginTime;
            log.info("Audio By Video Run Success, VideoFileName={}, Time Consuming={}s",videoSourceFilePath, timeConsuming/1000);
            return true;
        } catch (Exception e) {
            log.error("Audio By Video Run Error! VideoFileName={}", videoSourceFilePath, e);
            return false;
        }
    }
}
